/* $RCSfile: $
* Created on 2009-04-15 by Ziutek
* $Source: $
* $Id: $
* Copyright (c) 2005 Jiffle Ltd.  All rights reserved.
*/ 
package pl.kane.autokomp.livegenerator.dto;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/** 
 * Extended class loader. Allows multiple loads of compiled class.
 * @author Lukasz Wator
 * @version $Revision: 1.0
 */
public class MyClassLoader extends ClassLoader{
	String rootPath;
	String generationClass;

    public MyClassLoader(ClassLoader parent, String rootPath, String generationClass) {
    	 super(parent);
    	this.rootPath = rootPath;
    	this.generationClass = generationClass;
       
    }

    public Class loadClass(String name) throws ClassNotFoundException {
       
    	if(!generationClass.equals(name))
            return super.loadClass(name);


        try {
            String url = "file:"+rootPath+name.replace('.','/')+".class";
            URL myUrl = new URL(url);
            URLConnection connection = myUrl.openConnection();
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();

            while(data != -1){
                buffer.write(data);
                data = input.read();
            }

            input.close();

            byte[] classData = buffer.toByteArray();

            return defineClass(name,
                    classData, 0, classData.length);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace(); 
        }

        return null;
    }

}
